/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@Unique(['ARTICLE, CATEGORY'])
public class CategoryIndex {
    Article article
    Category category

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof CategoryIndex && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE CategoryIndex (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT CATEGORYINDEX_PK PRIMARY KEY, Article INT NOT NULL, Category INT NOT NULL)")
        
        execute('CREATE UNIQUE INDEX UIX_ARTICLE_CATEGORY__CATEGORYINDEX ON CategoryIndex (ARTICLE, CATEGORY)')
        
    }

    boolean isValid() {
        article != null && category != null
    }


    boolean isConflicted() {
    
        def idUIX_ARTICLE_CATEGORY = findIdByUIX_ARTICLE_CATEGORY(aRTICLE, cATEGORY)
        if(idUIX_ARTICLE_CATEGORY != null && idUIX_ARTICLE_CATEGORY != id) return true
    
        false
    }

    
    Integer findIdByUIX_ARTICLE_CATEGORY(aRTICLE, cATEGORY) {
        firstRow("SELECT ID FROM CategoryIndex WHERE ARTICLE = $aRTICLE AND CATEGORY = $cATEGORY")?.id
    }
    


    static CategoryIndex create(article, category) {
        def instance = new CategoryIndex(article: article, category: category)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO CategoryIndex (Article, Category) VALUES (${article?.getId()}, ${category?.getId()})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static CategoryIndex find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM CategoryIndex WHERE Id = $id")
        
        row ? new CategoryIndex(id: row.Id, article: Article.find((Short)row.article), category: Category.find((Short)row.category)) : null
        
    }

    static ArrayList<CategoryIndex> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new CategoryIndex(id: row.Id, article: Article.find((Short)row.article), category: Category.find((Short)row.category))
        }
        
        rows
    }

    static ArrayList<CategoryIndex> findAll() {
        findBySql('SELECT * FROM CategoryIndex')
    }

    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE CategoryIndex SET Article = ${article?.getId()}, Category = ${category?.getId()} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM CategoryIndex WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<CategoryIndex> findByArticle(value) {
        findBySql("SELECT * FROM CategoryIndex WHERE Article = ${value?.getId()}")
    }

    static ArrayList<CategoryIndex> findByCategory(value) {
        findBySql("SELECT * FROM CategoryIndex WHERE Category = ${value?.getId()}")
    }



    static ArrayList<CategoryIndex> findByArticleLike(String keyword) {
        findBySql("SELECT * FROM CategoryIndex WHERE Article LIKE $keyword")
    }

    static ArrayList<CategoryIndex> findByCategoryLike(String keyword) {
        findBySql("SELECT * FROM CategoryIndex WHERE Category LIKE $keyword")
    }



    def updateArticle(value) {
        this.article = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE CategoryIndex SET Article = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateCategory(value) {
        this.category = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE CategoryIndex SET Category = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    // </editor-fold>
}
